package cn.jobstart.common.http;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Created by ningbohezhijun on 16/5/13.
 */
public class AuthPostForm {
    private static final Logger log = LoggerFactory.getLogger(AuthPostForm.class);

    public static <T> T authPostForm(String url, List<NameValuePair> nameValuePairs, Class<T> returnType, int soTimeout, int conTimeout, String... headers) {
        HttpClient httpClient =  HttpRequest.getHttpClient();

        HttpPost post = new HttpPost(url);
        post.setHeader(HTTP.CONTENT_TYPE,"application/x-www-form-urlencoded;charset=UTF-8");
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, conTimeout);
        post.setParams(params);
        try {
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            return execute(httpClient, post, returnType, headers);
        } catch (UnsupportedEncodingException e) {
            log.warn("process url={} error {}", url, e);
            throw new RuntimeException("UnsupportedEncodingException(utf-8)", e);
        }
    }

    public static <T> T execute(HttpClient httpClient, HttpUriRequest req, Class<T> returnType, String... headers) {

        try {
            // 插入basic验证等基础逻辑
            for (int i = 0; i < headers.length; i += 2) {
                req.addHeader(headers[i], headers[i + 1]);
            }
            HttpResponse jres = httpClient.execute(req);

            HttpEntity ent = jres.getEntity();
            String content = ent != null ? EntityUtils.toString(ent, "UTF-8") : null;
            if (jres.getStatusLine().getStatusCode() >= 200
                    && jres.getStatusLine().getStatusCode() < 300) {
                if (returnType == String.class) {
                    return (T) content;
                }
                return JSON.parseObject(content, returnType);
            } else {
                log.warn("error response code={}", new Object[]{jres.getStatusLine().getStatusCode()});
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("request error,", e);
        }
        return null;
    }

    public static <T> T tryAuthPostForm(String url, List<NameValuePair> nameValuePairs, Class<T> returnType, int soTimeout, int conTimeout, String... headers) {
        int tryCount = 3;
        while (tryCount-- > 0) {
            try {
                return authPostForm(url, nameValuePairs, returnType, soTimeout, conTimeout, headers);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
    }
}
